package com.jfzt.utils;

import com.alibaba.fastjson2.JSONObject;
import com.jfzt.config.Loggable;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

/**
 * AOP切面拦截器
 * @author: shunpeng.hu
 * @date: 2024/4/10 11:27
 */
@Aspect
@Component
@Slf4j
public class LogAspect {


//    @Around("@annotation(loggable)")
//    public Object logExecutionTime(ProceedingJoinPoint joinPoint, Loggable loggable) throws Throwable {
//        long start = System.currentTimeMillis();
//
//        Object proceed = joinPoint.proceed(); // 执行目标方法
//
//        long executionTime = System.currentTimeMillis() - start;
//
//        // 记录日志的逻辑
//        log.info(joinPoint.getSignature() + " executed in " + executionTime + "ms");
//
//        return proceed;
//    }

    @Around("@annotation(loggable)")
    public Object logBusinessOperation(ProceedingJoinPoint joinPoint, Loggable loggable) throws Throwable {
        // 方法执行前的逻辑，例如记录开始时间、方法参数等
        long start = System.currentTimeMillis();
        try {
            // 校验Es
            Object result = joinPoint.proceed(); // 执行目标方法

            String json = JsonUtils.objectToJson(result);
            log.info("json:{}", json);
            JSONObject esJsonObject = JSONObject.parseObject(json);
            log.info("jsonObject:{}", esJsonObject);

            ElasticsearchServiceImplUtils.commonWriteElasticSearch(null, esJsonObject, null);

            // 方法执行后的逻辑，例如记录结束时间、返回值等
            return result;
        } catch (Exception e) {
            // 异常处理逻辑，如记录异常信息
            throw e;
        } finally {
            long executionTime = System.currentTimeMillis() - start;
            // 构建日志信息并记录
            log.info("{} executed in {} ms", joinPoint.getSignature(), executionTime);
        }
    }

}
